﻿using CommunityToolkit.Mvvm.ComponentModel;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace KeZhou.Models
{
    internal class CityDataDao
    {
        private static string mySqlConnectStr = "server=www.yym-free.com;Database =kezhou;uid=kezhou;pwd=10708022;charset=utf8";
        private MySqlConnection mySqlConn;

        // cityName: 城市名称，不带“市”
        // type: 景区、必吃、必逛
        public List<POI> getCityDatas(string cityName, string type)
        {
            if (cityName.EndsWith("市"))
                cityName = cityName.Substring(0, cityName.Length - 1);
            string selectCmd = $"SELECT * FROM kezhou.city_data WHERE city_name='{cityName}' and type='{type}';";
            List<POI> results = new List<POI>();
            using (mySqlConn = new MySqlConnection(mySqlConnectStr))
            {
                mySqlConn.Open();
                using (var cmd = mySqlConn.CreateCommand())
                {
                    cmd.CommandText = selectCmd;
                    MySqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        POI poi = new POI();
                        poi.Name = reader["name"].ToString();
                        List<string> rateAndDescription = splitContent(reader["content"].ToString());
                        poi.Rate = double.Parse(rateAndDescription[0]);
                        poi.Description = rateAndDescription[1];
                        poi.Type = type;
                        poi.Lng = reader.GetDouble("lng");
                        poi.Lat = reader.GetDouble("lat");
                        results.Add(poi);
                    }
                    reader.Close();
                }
            }
            return results;
        }

        // 将content字段分成评分和简介
        private List<string> splitContent(string content)
        {
            List<string> result = new List<string>();
            string pattern = @"^([\d.]+)分(.*)条点评(.*)$";
            Match match = Regex.Match(content, pattern);

            if (match.Success)
            {
                string rating = match.Groups[1].Value;  // 提取评分
                string description = match.Groups[3].Value;  // 提取描述
                result.Add(rating);
                result.Add(description);
            }
            return result;
        }
    }

}
